package com.hm.common.exception;


import com.hm.business.vo.ResultVO;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
* @Description: Validate配合全局异常
* @param
* @return
* @throws
* @author Coder编程
* @date 2021/6/17 13:35
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
	@ExceptionHandler(value = ConstraintViolationException.class)
	public ResultVO handle1(ConstraintViolationException ex) {
		StringBuilder msg = new StringBuilder();
		Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
		for (ConstraintViolation<?> constraintViolation : constraintViolations) {
			PathImpl pathImpl = (PathImpl) constraintViolation.getPropertyPath();
			String paramName = pathImpl.getLeafNode().getName();
			String message = constraintViolation.getMessage();
			msg.append("[").append(message).append("]");
		}
		return new ResultVO(200, msg.toString());
	}
 
	@ExceptionHandler(value = Exception.class)
	public ResultVO handle1(Exception ex) {
		ex.printStackTrace();
		return new ResultVO(404, ex.getMessage());
	}
	
	@ExceptionHandler(ArithmeticException.class)
	public ResultVO handle2(Exception ex) {
		return new ResultVO(404, "运算异常");
	}
 
	@ExceptionHandler(BindException.class)
	public ResultVO exceptionHandler(BindException e, HttpServletRequest request) {
		String failMsg = e.getBindingResult().getFieldError().getDefaultMessage();
		return new ResultVO(404, failMsg);
	}
}